import { http } from '@/utils/request';

// TypeScript 类型定义
export interface ApiResponse<T = any> {
  code: number;
  message: string;
  data: T;
  timestamp: number;
}

export interface LoginRequest {
  username: string;
  password: string;
}

export interface RegisterRequest {
  username: string;
  password: string;
  nickname: string;
  phone: string;
  verifyCode: string;
}

export interface UserInfo {
  id: number;
  username: string;
  nickname: string;
  avatar: string;
  phone: string;
  email: string;
  level?: number;
  experience?: number;
  totalStudyTime?: number;
  practiceCount?: number;
  achievements?: string[];
}

export interface Banner {
  id: number;
  title: string;
  description: string;
  image: string;
  link: string;
  sort: number;
  status: string;
}

export interface FunctionModule {
  key: string;
  name: string;
  icon: string;
  bgColor: string;
  iconColor: string;
  route: string;
  sort: number;
  enabled: boolean;
}

export interface Course {
  id: number;
  title: string;
  description: string;
  cover: string;
  instructor?: string | null;
  rating: string | number;
  studentCount?: number;
  student_count?: number; // 后端字段
  studyCount?: number;
  duration: number;
  difficulty: string;
  categoryId?: number;
  category_id?: number; // 后端字段
  price?: string | number;
  original_price?: string | number; // 后端字段
  originalPrice?: number;
  tags?: string[];
  lesson_count?: number; // 后端字段
  content_url?: string | null; // 后端字段
  is_featured?: boolean; // 后端字段
  is_active?: boolean; // 后端字段
  progress?: number;
  isEnrolled?: boolean;
  isRecommended?: boolean;
  type?: string;
  createdAt?: string;
  created_at?: string; // 后端字段
  updatedAt?: string;
  updated_at?: string; // 后端字段
  category?: {
    id: number;
    name: string;
    description: string;
    icon: string;
    sort: number;
    is_active: boolean;
    created_at: string;
    updated_at: string;
  };
}

export interface Activity {
  id: number;
  title: string;
  description: string;
  poster: string;
  startTime: string;
  endTime: string;
  status: string;
  participantCount: number;
}

export interface Category {
  id: number;
  name: string;
  icon: string;
  color: string;
  courseCount: number;
  sort: number;
}

export interface PaginationParams {
  page: number;
  limit: number;
}

export interface PaginationResponse<T> {
  list: T[];
  total: number;
  page: number;
  limit: number;
}

// ==================== 用户认证模块 ====================

/**
 * 用户登录
 */
export function login(data: LoginRequest) {
  return http.post<ApiResponse<{
    token: string;
    refreshToken: string;
    expiresIn: number;
    userInfo: UserInfo;
  }>>('/auth/login', data);
}

/**
 * 发送验证码
 */
export function sendVerificationCode(data: { phone: string }) {
  return http.post<ApiResponse<{ message: string }>>('/auth/send-code', data);
}

/**
 * 用户注册
 */
export function register(data: RegisterRequest) {
  return http.post<ApiResponse<{ message: string }>>('/auth/register', data);
}

/**
 * 获取用户信息
 */
export function getUserProfile() {
  return http.get<ApiResponse<UserInfo>>('/auth/profile');
}

/**
 * 刷新Token
 */
export function refreshToken(refreshToken: string) {
  return http.post<ApiResponse<{ token: string; expiresIn: number }>>('/auth/refresh', {
    refreshToken
  });
}

/**
 * 用户登出
 */
export function logout() {
  return http.post<ApiResponse<{}>>('/auth/logout');
}

// ==================== 首页模块 ====================

/**
 * 获取轮播图
 */
export function getBanners() {
  return http.get<ApiResponse<Banner[]>>('/home/banners');
}

/**
 * 获取功能模块
 */
export function getFunctions() {
  return http.get<ApiResponse<FunctionModule[]>>('/home/functions');
}

/**
 * 获取推荐内容
 */
export function getRecommendations(params: PaginationParams) {
  return http.get<ApiResponse<PaginationResponse<Course>>>('/home/recommendations', { params });
}

/**
 * 获取活动列表
 */
export function getActivities() {
  return http.get<ApiResponse<Activity[]>>('/home/activities');
}

// ==================== 学习中心模块 ====================

/**
 * 获取课程分类
 */
export function getCourseCategories() {
  return http.get<ApiResponse<Category[]>>('/study/categories');
}

/**
 * 获取推荐课程
 */
export function getRecommendedCourses(params: PaginationParams & {
  category?: string;
  difficulty?: string;
}) {
  return http.get<ApiResponse<PaginationResponse<Course>>>('/study/courses/recommended', { params });
}

/**
 * 搜索课程
 */
export function searchCourses(params: PaginationParams & {
  keyword: string;
  category?: string;
  difficulty?: string;
  sortBy?: string;
}) {
  return http.get<ApiResponse<PaginationResponse<Course>>>('/study/courses/search', { params });
}

/**
 * 获取课程详情
 */
export function getCourseDetail(id: number) {
  return http.get<ApiResponse<Course>>(`/study/courses/${id}`);
}

/**
 * 获取用户学习进度
 */
export function getUserProgress(courseId: number) {
  return http.get<ApiResponse<{
    courseId: number;
    progress: number;
    completedLessons: number;
    totalLessons: number;
    studyTime: number;
    lastStudyTime: string;
  }>>(`/study/progress/${courseId}`);
}

/**
 * 更新学习进度
 */
export function updateProgress(data: {
  courseId: number;
  lessonId: number;
  progress: number;
  studyTime: number;
}) {
  return http.post<ApiResponse<{}>>('/study/progress', data);
}

// ==================== 语音检测模块 ====================

export interface DetectionText {
  id: number;
  title: string;
  content: string;
  pinyin: string;
  level: string;
  category: string;
  duration: number;
  standardAudio: string;
}

export interface EvaluationResult {
  id: number;
  textId: number;
  score: number;
  level: string;
  accuracy: number;
  fluency: number;
  completeness: number;
  suggestions: string[];
  detailScores: Array<{
    word: string;
    score: number;
    issues: string[];
  }>;
  audioUrl: string;
  createdAt: string;
}

export interface EvaluationHistory {
  id: number;
  textTitle: string;
  score: number;
  level: string;
  duration: number;
  createdAt: string;
}

/**
 * 获取检测文本
 */
export function getDetectionTexts(params?: {
  level?: string;
  category?: string;
}) {
  return http.get<ApiResponse<DetectionText[]>>('/detection/texts', { params });
}

/**
 * 提交语音评测
 */
export function submitVoiceEvaluation(data: FormData) {
  return http.post<ApiResponse<EvaluationResult>>('/detection/evaluate', data, {
    headers: { 'Content-Type': 'multipart/form-data' }
  });
}

/**
 * 获取评测历史
 */
export function getDetectionHistory(params: PaginationParams & {
  startDate?: string;
  endDate?: string;
}) {
  return http.get<ApiResponse<PaginationResponse<EvaluationHistory> & {
    statistics: {
      averageScore: number;
      totalPractices: number;
      bestScore: number;
      improvementRate: number;
    };
  }>>('/detection/history', { params });
}

// ==================== 小游戏模块 ====================

export interface GameContent {
  id: number;
  image: string;
  pinyin: string;
  standardText: string;
  level: string;
  category: string;
  audioUrl: string;
}

export interface GameResult {
  id: number;
  contentId: number;
  userPronunciation: string;
  standardPronunciation: string;
  similarity: number;
  score: number;
  level: string;
  suggestions: string[];
  createdAt: string;
}

export interface GameRecord {
  id: number;
  contentTitle: string;
  score: number;
  level: string;
  createdAt: string;
}

/**
 * 获取游戏内容
 */
export function getGameContents(params?: {
  level?: string;
  category?: string;
}) {
  return http.get<ApiResponse<GameContent[]>>('/game/contents', { params });
}

/**
 * 提交游戏结果
 */
export function submitGameResult(data: FormData) {
  return http.post<ApiResponse<GameResult>>('/game/submit', data, {
    headers: { 'Content-Type': 'multipart/form-data' }
  });
}

/**
 * 获取游戏记录
 */
export function getGameRecords(params: PaginationParams) {
  return http.get<ApiResponse<PaginationResponse<GameRecord> & {
    statistics: {
      totalGames: number;
      averageScore: number;
      bestScore: number;
      favoriteCategory: string;
    };
  }>>('/game/records', { params });
}

// ==================== 每日一句模块 ====================

export interface DailySentence {
  id: number;
  date: string;
  chinese: string;
  pinyin: string;
  english: string;
  source: string;
  audioUrl: string;
  difficulty: string;
  category?: string;
  tags: string[];
}

export interface DailySubmission {
  id: number;
  sentenceId: number;
  score: number;
  level: string;
  accuracy: number;
  fluency: number;
  completeness: number;
  videoUrl: string;
  suggestions: string[];
  createdAt: string;
}

export interface DailyHistory {
  id: number;
  date: string;
  sentence: string;
  score: number;
  level: string;
  createdAt: string;
}

/**
 * 获取每日一句
 */
export function getDailySentence(params?: { date?: string }) {
  return http.get<ApiResponse<DailySentence>>('/daily/sentence', { params });
}

/**
 * 上传音频文件
 */
export function uploadAudio(data: FormData) {
  return http.post<ApiResponse<{ url: string; filename: string }>>('/upload/audio', data);
}

/**
 * 上传视频文件
 */
export function uploadVideo(data: FormData) {
  return http.post<ApiResponse<{ url: string; filename: string }>>('/upload/video', data);
}

/**
 * 提交每日朗读
 */
export function submitDailyReading(data: FormData | {
  sentenceId: number;
  videoUrl?: string;
  audioUrl?: string;
  duration?: number;
  submissionDate: string;
}) {
  return http.post<ApiResponse<DailySubmission>>('/daily/submit', data);
}

/**
 * 获取朗读历史
 */
export function getDailyHistory(params: PaginationParams & {
  month?: string;
}) {
  return http.get<ApiResponse<PaginationResponse<DailyHistory> & {
    statistics: {
      continuousDays: number;
      totalDays: number;
      averageScore: number;
      bestScore: number;
      thisMonthDays: number;
    };
  }>>('/daily/history', { params });
}

// ==================== 通知消息模块 ====================

export interface Notification {
  id: number;
  title: string;
  content: string;
  type: string;
  status: string;
  createdAt: string;
  extra?: Record<string, any>;
}

/**
 * 获取消息列表
 */
export function getNotifications(params: PaginationParams & {
  type?: string;
  status?: string;
}) {
  return http.get<ApiResponse<PaginationResponse<Notification> & {
    unreadCount: number;
  }>>('/notifications', { params });
}

/**
 * 标记消息已读
 */
export function markNotificationRead(id: number) {
  return http.put<ApiResponse<{}>>(`/notifications/${id}/read`);
}

/**
 * 批量标记已读
 */
export function markAllNotificationsRead() {
  return http.put<ApiResponse<{}>>('/notifications/read-all');
}

// ==================== 数据统计模块 ====================

export interface StudyStatistics {
  totalStudyTime: number;
  totalPractices: number;
  averageScore: number;
  continuousDays: number;
  weeklyData: Array<{
    date: string;
    studyTime: number;
    practiceCount: number;
    averageScore: number;
  }>;
  categoryStats: Array<{
    category: string;
    practiceCount: number;
    averageScore: number;
    totalTime: number;
  }>;
  achievements: Array<{
    id: number;
    name: string;
    description: string;
    icon: string;
    unlockedAt: string;
  }>;
}

export interface UserOverallStats {
  level: number;
  experience: number;
  nextLevelExp: number;
  totalStudyTime: number;
  totalPractices: number;
  averageScore: number;
  rank: number;
  totalUsers: number;
  badges: string[];
  streakDays: number;
  maxStreakDays: number;
}

/**
 * 获取学习统计
 */
export function getStudyStatistics(params?: { period?: string }) {
  return http.get<ApiResponse<StudyStatistics>>('/statistics/study', { params });
}

/**
 * 获取用户总体统计
 */
export function getUserStatistics() {
  return http.get<ApiResponse<UserOverallStats>>('/statistics/user');
}

/**
 * 获取排行榜
 */
export function getLeaderboard(params: {
  type: string; // score/time/practice
  period: string; // week/month/all
  page: number;
  limit: number;
}) {
  return http.get<ApiResponse<PaginationResponse<{
    rank: number;
    userId: number;
    nickname: string;
    avatar: string;
    score: number;
    value: number;
  }>>>('/statistics/leaderboard', { params });
}

// ==================== 文件上传模块 ====================

export interface UploadResult {
  url: string;
  filename: string;
  size: number;
  type: string;
  duration?: number; // 音频/视频时长
}

/**
 * 文件上传
 */
export function uploadFile(data: FormData) {
  return http.post<ApiResponse<UploadResult>>('/upload', data, {
    headers: { 'Content-Type': 'multipart/form-data' }
  });
}

/**
 * 批量文件上传
 */
export function uploadFiles(data: FormData) {
  return http.post<ApiResponse<UploadResult[]>>('/upload/batch', data, {
    headers: { 'Content-Type': 'multipart/form-data' }
  });
}

/**
 * 获取上传进度
 */
export function getUploadProgress(uploadId: string) {
  return http.get<ApiResponse<{
    uploadId: string;
    progress: number;
    status: string;
    message?: string;
  }>>(`/upload/progress/${uploadId}`);
}

// ==================== 系统配置模块 ====================

/**
 * 获取应用配置
 */
export function getAppConfig() {
  return http.get<ApiResponse<{
    version: string;
    features: Record<string, boolean>;
    limits: {
      maxFileSize: number;
      maxRecordingDuration: number;
      dailyPracticeLimit: number;
    };
    urls: {
      helpCenter: string;
      privacy: string;
      terms: string;
    };
  }>>('/config/app');
}

/**
 * 获取系统公告
 */
export function getSystemAnnouncements() {
  return http.get<ApiResponse<Array<{
    id: number;
    title: string;
    content: string;
    type: string;
    priority: number;
    startTime: string;
    endTime: string;
    status: string;
  }>>>('/config/announcements');
}

// ==================== 兼容性接口 ====================

/**
 * 账号密码登录 (保留原有接口)
 * @deprecated 请使用 login 接口
 */
export function loginPassword() {
  return http.post(`/api/login`, {
    data: { name: '123' },
  });
}
